package com.mybatisflex.util;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class EncryptUtil {
    private static final String RSA_ALGORITHM = "RSA";

    // TODO: 替换为你的实际公钥和私钥字符串
    private static final String publicKeyString =
        "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCLX6V9R2JyGkv7UGsoPvhw/BXVgBWkaN37xT6USmeLGzAW0itLzbPtBt8ZY1JFOKnnNc/NkcGUi2o21mFhpmkKEtyRzmPFd2LLqmQ1rMCXd7Z6P+XWzavzKoacHTJzvS7tIx9vwbbTylrMpcD4JL7EQp8+oMUC/bnS/lv/94qA1QIDAQAB";
    private static final String privateKeyString =
        "MIICcwIBADANBgkqhkiG9w0BAQEFAASCAl0wggJZAgEAAoGBAItfpX1HYnIaS/tQayg++HD8FdWAFaRo3fvFPpRKZ4sbMBbSK0vNs+0G3xljUkU4qec1z82RwZSLajbWYWGmaQoS3JHOY8V3YsuqZDWswJd3tno/5dbNq/MqhpwdMnO9Lu0jH2/BttPKWsylwPgkvsRCnz6gxQL9udL+W//3ioDVAgMBAAECf3pgY3up6dxgIRuOY1WRKFiVREFQ7WueDyn+YN8QIHzVVb3nO4vxsH3Z289iLvAp7sEzT9isc/OPutnanwT4rp77UKWXdvIKhT03JZvEbRp+ShTADw8h6hJ3kji61UAPX15aa8n4VCZW7pnjquMFG+24VRgEx23LSzTLTn6Rc2ECQQCxxID/hlF2JPxsDN8GXQ4FizfG0CT1CcVVGP3FgsMtVIIRqkLVB9KFwk7qRZSPqCOG+bsUgTfOyaJw48Xk6/R1AkEAyLWiZ9Jh/DF5rFWaW93xNpN1OL/2/F4Rr8vHQ9Of+vA7qWU4oIx5eWwV6ykdD/Vpjy4RbnUNg/LKKZ0Z91lO4QJAcPgfwkLpodr/TusfEDwynPNMDtxXoCEFdn7bRplCz5vUzMUWk6rU7ov8+oQdVO3VJgGuEenMPW2F/ZfCOyh3wQJAcLawEaXwKPSP49ve56BoCcIdnlUPmwIo5JSHvutleELY/nQ9rMu2nB264WkhTQkA0suINoO9p0/9gAkdv+6DgQJAIjSQAUEMFzmgQKmRIlLHTcEcU85Lp6jnPp/vW8D2WqLVthvQCVBlShQJzCTVTS3RV4n21WlpOiR/I5fGdm4+WQ==";

    // 获取公钥
    public static PublicKey getPublicKey() {
        byte[] keyBytes = Base64.getDecoder().decode(publicKeyString);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = null;
        try {
            keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
            return keyFactory.generatePublic(keySpec);
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            throw new RuntimeException(e);
        }
    }

    // 获取私钥
    public static PrivateKey getPrivateKey() throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(privateKeyString);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        return keyFactory.generatePrivate(keySpec);
    }

    // 加密方法
    public static String encrypt(String plainText) {
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, getPublicKey());
            byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
            return Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException | InvalidKeyException e) {
            throw new RuntimeException(e);
        }

    }

    // 解密方法
    public static String decrypt(String cipherText) {
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance(RSA_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, getPrivateKey());
            byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(cipherText));
            return new String(decryptedBytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    public static void main(String[] args) throws Exception {
        // 创建 KeyPairGenerator 实例
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");

        // 初始化 KeyPairGenerator
        keyPairGenerator.initialize(1024);

        // 生成密钥对
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        // 获取公钥和私钥
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();

        // 将公钥转换为 Base64 编码的字符串
        String publicKeyBase64 = Base64.getEncoder().encodeToString(publicKey.getEncoded());
        System.out.println("公钥(Base64)：" + publicKeyBase64);

        // 将私钥转换为 Base64 编码的字符串
        String privateKeyBase64 = Base64.getEncoder().encodeToString(privateKey.getEncoded());
        System.out.println("私钥(Base64)：" + privateKeyBase64);
    }
}